package com.kjlink.internal.report4vue.task;

import cn.xuqiudong.common.base.vo.BooleanWithMsg;
import cn.xuqiudong.quartz.annotation.TaskJobFlag;
import cn.xuqiudong.quartz.enums.TaskJobResult;
import cn.xuqiudong.quartz.job.AbstractTaskJob;
import cn.xuqiudong.quartz.model.TaskJobLog;
import cn.xuqiudong.quartz.service.TaskJobLogDetailService;
import com.kjlink.internal.workreport.helper.ReportCommonHelper;
import com.kjlink.internal.workreport.helper.SessionHelper;
import com.kjlink.internal.workreport.project.model.Project;
import com.kjlink.internal.workreport.task.ProjectTimeStatsTask;
import com.kjlink.internal.workreport.task.handler.ProjectTimeStatsHandler;
import com.kjlink.internal.workreport.user.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 描述:
 * 项目工时统计
 *
 * @author Vic.xu
 * @see ProjectTimeStatsTask
 * @since 2025-01-23 9:44
 */
@Component
public class ProjectTimeStatisticsTask extends AbstractTaskJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectTimeStatsTask.class);

    @Resource
    private ProjectTimeStatsHandler projectTimeStatsHandler;

    @Resource
    private TaskJobLogDetailService taskJobLogDetailService;


    /**
     * 23点59分50秒执行一次统计: 50 59 23 * * *
     */
    @TaskJobFlag(value = "project.stats.hours", text = "统计项目工时:总工时、年工时、月工时")
    public String statistics(TaskJobLog taskJobLog) {

        List<Project> projects = projectTimeStatsHandler.noneClosedProjects();
        if (CollectionUtils.isEmpty(projects)) {
            String msg = "没有项目需要统计工时";
            LOGGER.info(msg);
            return msg;
        }
        SessionHelper.storeUser2InheritableLocal(User.JOB_USER);
        try {
            StopWatch watch = new StopWatch();
            watch.start();
            LOGGER.info("start statistics project work times, project size = {}", projects.size());
            LocalDateTime now = LocalDateTime.now();
            int year = now.getYear();
            int month = now.getMonthValue();
            //形如202401  202412
            int monthDate = ReportCommonHelper.toMonthDate(year, month);
            projects.forEach(project -> {
                String msg = "统计项目[" + project.getName() + "]:";
                //1. 统计总工时
                BooleanWithMsg total = projectTimeStatsHandler.updateTotalTime(project);
                if (total.isSuccess()) {
                    msg += "总工时为[" + total.getMessage() + "]小时,";
                } else {
                    msg += "总工时失败,原因为[" + total.getMessage() + "]";
                }
                //2. 统计年工时
                BooleanWithMsg yearTime = projectTimeStatsHandler.updateYearUsedTime(project, year);
                if (yearTime.isSuccess()) {
                    msg += "年工时为[" + yearTime.getMessage() + "]小时,";
                } else {
                    msg += "年工时失败,原因为[" + yearTime.getMessage() + "]";
                }
                //3. 统计月工时
                BooleanWithMsg monthTime = projectTimeStatsHandler.updateMonthUsedTime(project, year, month, monthDate);
                if (monthTime.isSuccess()) {
                    msg += "月工时为[" + monthTime.getMessage() + "]小时,";
                } else {
                    msg += "月工时失败,原因为[" + monthTime.getMessage() + "]";
                }
                //记录日志详情
                taskJobLogDetailService.logDetail(taskJobLog, TaskJobResult.SUCCESS.name(), msg);
                LOGGER.info("统计项目[{}]的总工时为[{}]小时,年工时为[{}]小时,月工时为[{}]小时", project.getName(), total.getMessage(), yearTime.getMessage(), monthTime.getMessage());
            });
            watch.stop();
            LOGGER.info("statistics project work times finished, total size = {}, total time = {}s", projects.size(), watch.getTotalTimeSeconds());
            return "本次统计项目" + projects.size() + "个,耗时" + watch.getTotalTimeSeconds() + "秒";
        } finally {
            SessionHelper.cleanUserFromInheritableLocal();
        }
    }

}
